import Flutter
import UIKit

@objcMembers
public class FlutterLog : NSObject{

    static var logBuffer = [Any]()

    
    /// verbose level
    /// - Parameters:
    ///   - tag: tag
    ///   - msg: msg
    @objc public class func v(tag: String, msg: String) {
        log(level: "v", tag: tag, msg: msg)
    }
    
    /// debug level
    /// - Parameters:
    ///   - tag: tag
    ///   - msg: msg
    @objc public class func d(tag: String, msg: String) {
        log(level: "d", tag: tag, msg: msg)
    }

    
    /// info level
    /// - Parameters:
    ///   - tag: tag
    ///   - msg: msg
    @objc public class func i(tag: String, msg: String) {
        log(level: "i", tag: tag, msg: msg)
    }

    
    /// warn level
    /// - Parameters:
    ///   - tag: tag
    ///   - msg: msg
    @objc public class func w(tag: String, msg: String) {
        log(level: "w", tag: tag, msg: msg)
    }
    
    
    /// error level
    /// - Parameters:
    ///   - tag: tag
    ///   - msg: msg
    @objc public class func e(tag: String, msg: String) {
        log(level: "e", tag: tag, msg: msg)
    }

    static func log(level: String, tag: String, msg: String) {
        var params = [String:Any]()
        params["level"] = level
        params["tag"] = tag
        params["msg"] = msg
        params["timestamp"] = Int(Date().timeIntervalSince1970 * 1000)
        sendLogToFlutter(params: params)
    }

    
    static func sendLogToFlutter(params: [String:Any]) {
        if (SwiftMicrocosmLogPlugin.shared.flutterConnect) {
            SwiftMicrocosmLogPlugin.shared.sendMethodToFlutter(method: "log", arguments: params)
        } else {
            objc_sync_enter(self)
            logBuffer.append(params)
            objc_sync_exit(self)
            
            if(SwiftMicrocosmLogPlugin.shared.connectFlutterListener == nil) {
                SwiftMicrocosmLogPlugin.shared.connectFlutterListener = {
                    for item in self.logBuffer {
                        SwiftMicrocosmLogPlugin.shared.sendMethodToFlutter(method: "log", arguments: item)
                    }
                    self.logBuffer.removeAll()
                }
            }
        }
    }
}
